

import UIKit
import SwiftyUserDefaults
import SwiftyJSON

class LoginController: UIViewController {
    
    // 顶部的view
    lazy var topView: LoginTopView = {
        guard let topView = LoginTopView.newInstance() else {
            return LoginTopView()
        }
        topView.cancelBlock = { [unowned self] in
            self.dismiss(animated: true, completion: nil)
        }
        topView.cancelBtn.setTitleColor(kBtnGreen, for: .normal)
        return topView
    }()
    
    // MARK:- 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化
        self.setup()
    }
    
    lazy var service = UserService()
}

// MARK:- 初始化
extension LoginController {
    func setup() {
        // 设置背景颜色
        view.backgroundColor = UIColor.systemBackground
        
        view.addSubview(topView)
        
        
        let margin: CGFloat = 20.0
        // 登录
        let loginBtn = LXFBarButton(bgColor: kBtnGreen, disabledColor: kBtnDisabledGreen, title: "登录", titleColor: kBtnWhite, titleHighlightedColor: kBtnDisabledWhite)
        loginBtn.isEnabled = false
        view.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { (make) in
            make.top.equalTo(topView.snp.bottom).offset(margin * 0.5)
            make.left.equalTo(self.view).offset(margin)
            make.right.equalTo(self.view).offset(-margin)
            make.height.equalTo(48)
        }
        loginBtn.addTarget(self, action: #selector(login), for: .touchUpInside)
        
        // 设置登录按钮状态的回调
        topView.loginBtnBlock = {
            loginBtn.isEnabled = $0
        }
        
        // 短信验证码登录
        let smsLoginBtn = LXFLinkButton(title: "通过短信验证码登录", fontSize: 13)
        smsLoginBtn.isHidden = true
        view.addSubview(smsLoginBtn)
        
        
        topView.snp.makeConstraints { (make) in
            make.width.equalToSuperview()
            make.height.equalTo(300)
            make.centerX.equalToSuperview()
            if #available(iOS 11, *) {
                make.top.equalTo(self.view.safeAreaLayoutGuide)
            } else {
                make.top.equalTo(self.view)
            }
        }
        
        smsLoginBtn.snp.makeConstraints { (make) in
            make.top.equalTo(loginBtn.snp.bottom).offset(margin * 0.7)
            make.centerX.equalTo(self.view)
        }
        smsLoginBtn.addTarget(self, action: #selector(smsLogin), for: .touchUpInside)
        
        // 中间分割线
        let splitLine = UIView()
        splitLine.backgroundColor = kSplitLineColor
        splitLine.isHidden = true
        view.addSubview(splitLine)
        splitLine.snp.makeConstraints { (make) in
            make.height.equalTo(20)
            make.width.equalTo(1)
            if #available(iOS 11, *) {
                make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-margin * 1.5)
            } else {
                make.bottom.equalTo(self.view.snp.bottom).offset(-margin * 1.5)
            }
            make.centerX.equalTo(self.view.snp.centerX)
        }
        
        // 登录遇到问题
        let matterLoginBtn = LXFLinkButton(title: "登录遇到问题?", fontSize: 15)
        matterLoginBtn.isHidden = true
        view.addSubview(matterLoginBtn)
        matterLoginBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(splitLine.snp.centerY)
            make.right.equalTo(splitLine.snp.left).offset(-margin)
        }
        matterLoginBtn.addTarget(self, action: #selector(matterLogin), for: .touchUpInside)
        
        // 其他方法登录
        let otherLoginBtn = LXFLinkButton(title: "其他方法登录", fontSize: 15)
        otherLoginBtn.isHidden = true
        view.addSubview(otherLoginBtn)
        otherLoginBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(splitLine.snp.centerY)
            make.left.equalTo(splitLine.snp.right).offset(margin)
        }
        otherLoginBtn.addTarget(self, action: #selector(otherLogin), for: .touchUpInside)
    }
}

// MARK:- 事件处理
extension LoginController {
    @objc func login() {
        
        guard let account = topView.phoneF.text, let pwd = topView.pwdF.text else {
            return
        }
        
        // 注销第一响应者
        self.topView.phoneF.resignFirstResponder()
        self.topView.pwdF.resignFirstResponder()
        
        self.view.makeToastActivity(.center)
        
        IM.request(.login(userName:account,pwd:pwd), success: { (json) in
            if reqSuccess(json["code"].stringValue) { //如果操作成功
                self.loginSuccess(json)
            } else {
                DispatchQueue.main.async {
                    self.view.hideToastActivity()
                    self.view.makeToast(json["msg"].stringValue, duration: 3.0, position: .center)
                }
            }
        }, error: { (code) in
            print("请求错误！错误码：\(code)")
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                self.view.makeToast("登录失败", duration: 3.0, position: .center)
            }
        }) { (error) in
            print("请求失败！错误信息：\(error.errorDescription ?? "")")
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                self.view.makeToast("网络有问题，请稍后再试", duration: 3.0, position: .center)
            }
        }
    }
    
    
    func loginSuccess(_ json:JSON) {
        let userJson = json["res"]
        let uid = userJson["userId"].intValue
        let nickName = userJson["name"].stringValue
        let avatar = userJson["avatar"].stringValue
        let gender = userJson["gender"].stringValue
        
        self.service.login(uid, nickName,avatar:avatar,gender:gender)
        
        DispatchQueue.main.async {
            self.view.hideToastActivity()
            let tabBar = ChatTabBarController()
            UIApplication.shared.keyWindow?.rootViewController = tabBar
        }
    }
    
    
    
    
    @objc func smsLogin() {
        LXFLog("短信验证码登录")
    }
    @objc func matterLogin() {
        LXFLog("登录遇到问题")
    }
    @objc func otherLogin() {
        LXFLog("其他方法登录")
    }
}
